package server.simple100;


import org.junit.Test;

import java.util.ArrayList;
import java.util.List;


/**
 * [136]只出现一次的数字
 */
public class LeetCode155 {


    @Test
    public void test() {
        MinStack minStack = new MinStack();
        minStack.push(-2);
        minStack.push(0);
        minStack.push(-3);
        System.out.println(minStack.getMin());// --> 返回 -3.
        minStack.pop();
        System.out.println(minStack.top()); //--> 返回 0.
        System.out.println(minStack.getMin()); //--> 返回 -2.
    }


    class MinStack {
        List<Integer> list;
        Integer min = null;

        public MinStack() {
            list = new ArrayList<>();
        }

        public void push(int val) {
            list.add(val);
            if(min != null && val < min){
                min = val;
            }
        }

        public void pop() {
            list.remove(list.size() - 1);
            min = null;
        }

        public int top() {
            return list.get(list.size() - 1);
        }

        public int getMin() {
            if (min == null) {
                jsMin();
            }
            return min;
        }

        public void jsMin() {
            if (list.size() == 0) {
                min = null;
            }
            int minNum = list.get(0);
            for (int i = 0; i < list.size(); i++) {
                if (minNum > list.get(i)) {
                    minNum = list.get(i);
                }
            }
            min = minNum;
        }
    }
}
